package com.heima.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.search.vos.SearchArticleVo;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.SearchService;
import com.heima.utils.thread.ApThreadLocalUtil;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author DiXiaoNie
 * @since 2023/1/2 11:35
 */
@Service
public class SearchServiceImpl implements SearchService {
    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private ApUserSearchService apUserSearchService;

    /**
     * 添加文章到es中
     *
     * @param vo 签证官
     * @author DiXiaoNie
     * @date 2023/01/02
     */
    @Override
    public void addArticleToEs(SearchArticleVo vo) {
        //2.创建添加文档请求对象，并指定索引库名
        IndexRequest indexRequest = new IndexRequest("app_info_article");
        indexRequest.id(vo.getId().toString());
        indexRequest.source(JSON.toJSONString(vo), XContentType.JSON);
        //1.调用es的添加文档的api
        try {
            client.index(indexRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 搜索
     *
     * @param dto dto
     * @return {@link ResponseResult }
     * @author DiXiaoNie
     * @date 2023/01/02
     */
    @Override
    public ResponseResult search(UserSearchDto dto) {
        ApUser apUser = ApThreadLocalUtil.getApUserThreadLocal();
        if (apUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }

        //异步调用保存历史记录
        this.apUserSearchService.insert(dto.getSearchWords(), apUser.getId());

        //1.根据条件执行search查询方法

        //1.2创建搜索请求对象，指定索引库名称
        SearchRequest searchRequest = new SearchRequest("app_info_article");
        //1.3封装条件
        BoolQueryBuilder builder = QueryBuilders.boolQuery();
        //根据关键字查询
        if (dto.getSearchWords() == null) {
            builder.filter(QueryBuilders.matchAllQuery());
        } else {
            builder.filter(QueryBuilders.matchQuery("all", dto.getSearchWords()));
        }

        //根据时间查询
        if (dto.getMinBehotTime() != null) {
            builder.filter(QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime().getTime()));

        }
        searchRequest.source().query(builder);

        //根据时间倒叙展示
        searchRequest.source().sort("publishTime", SortOrder.DESC);
        //分页
        searchRequest.source().from(dto.getPageNum()).size(dto.getPageSize());
        //高亮
        searchRequest.source().highlighter(SearchSourceBuilder.highlight()
                //指定高亮的域
                .field("title")
                //高亮样式
                .preTags("<font style='color: red; font-size: inherit;'>")
                .postTags("</font>")
                .requireFieldMatch(false));

        //1.1 调接口
        try {
            SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

            //2.结果封装
            List<Map> list = new ArrayList<>();

            SearchHit[] hits = searchResponse.getHits().getHits();
            for (SearchHit hit : hits) {
                Map<String, Object> sourceAsMap = hit.getSourceAsMap();
                //做高亮设置
                //1。取出高亮域
                HighlightField highlightField = hit.getHighlightFields().get("title");
                if (highlightField != null && highlightField.getFragments().length > 0) {
                    Text highlightFieldTitle = highlightField.getFragments()[0];
                    sourceAsMap.put("h_title", highlightFieldTitle.toString());
                } else {
                    sourceAsMap.put("h_title", sourceAsMap.get("title"));
                }
                list.add(sourceAsMap);
            }


            return ResponseResult.okResult(list);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
    }

}
